/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { BreakpointManager } from '../../hooks/breakpoint';
import { Breakpoint } from '../../types/breakpoint';
import { AttributeManager } from '../../hooks/attributeManager';
import { EventManager } from '../../hooks/eventManager';
import { defaultBreakConfig, defaultConfig } from './default';

/**
 * @description 基于web components实现页签栏组件父标签
 */
export class TabBarComponent extends HTMLElement {
  private _property: string[];
  private _elementId: string;
  private _styleElement: HTMLStyleElement | null;
  private _currentBreakpoint: Breakpoint;
  private _unsubscribeBreakpoint: () => void;
  private _attributeManager: AttributeManager;
  private _eventManager: EventManager;
  private _selectedItem: string;
  private _observer: MutationObserver;

  constructor() {
    super();
    this._styleElement = null;
    this._property = ['scope', 'width', 'height', 'unselected-color', 'selected-color', 'layout-mode', 'vertical-align', 'horizontal-align', 'bg-color', 'selected-bg-color'];
    this._elementId = '';
    this._attributeManager = new AttributeManager();
    this._eventManager = new EventManager(this);
    this._selectedItem = '';
    this._observer = new MutationObserver((mutations) => {
      mutations.forEach(mutation => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'vertical') {
          this._attachStyles();
        }
      });
    });
    const breakpointManager = new BreakpointManager();
    this._currentBreakpoint = 'sm';
    this._unsubscribeBreakpoint = breakpointManager.subscribeToBreakpoint((bp) => {
      this._currentBreakpoint = bp;
      this._attachStyles();
    })
  }

  connectedCallback(): void {
    const parent = this.parentNode as HTMLElement;
    this._observer.observe(parent, { attributes: true });

    const navItems = this.querySelectorAll('tab-bar-item');
    if (navItems.length) {
      this._selectedItem = this.getAttribute('value') || navItems[0].getAttribute('name') || '';   
    }
    this._attachStyles();
  }

  disconnectedCallback(): void {
    this._unsubscribeBreakpoint();
    if (this._observer) {
      this._observer.disconnect();
    }
  }

  static get observedAttributes(): string[] {
    return ['scope', 'width', 'height', 'unselected-color', 'selected-color', 'layout-mode', 'vertical-align', 'horizontal-align', 'bg-color', 'selected-bg-color'];
  }

  attributeChangedCallback(name: string, oldValue: any, newValue: any): void {
    if (this._property.includes(name) && oldValue !== newValue) {
      this._attachStyles();
    }
  }

  private _attachStyles(): void {
    if (this._styleElement) {
      this._styleElement.remove();
    }

    const verticalAttr = this.parentNode ? (this.parentNode as HTMLElement).getAttribute('vertical') : '';
    const vertical = this._attributeManager.processBoolean(verticalAttr, defaultBreakConfig.container[this._currentBreakpoint].vertical);
    const width = this._attributeManager.processSize(this.getAttribute('width'), defaultBreakConfig.container[this._currentBreakpoint].width);
    const height = this._attributeManager.processSize(this.getAttribute('height'), defaultBreakConfig.container[this._currentBreakpoint].height);
    const unselectedColor = this._attributeManager.processColor(this.getAttribute('unselected-color'), defaultConfig.container.unselectedColor);
    const selectedColor = this._attributeManager.processColor(this.getAttribute('selected-color'), defaultConfig.container.selectedColor);
    const layoutMode = this._attributeManager.processMultiValues(this.getAttribute('layout-mode'), ['vertical', 'horizontal'], ['column', 'row'], defaultBreakConfig.container[this._currentBreakpoint].layoutMode);
    const verticalAlign = this._attributeManager.processMultiValues(this.getAttribute('vertical-align'), ['top', 'center', 'bottom'], ['flex-start', 'center', 'flex-end'], defaultConfig.container.verticalAlign);
    const horizontalAlign = this._attributeManager.processMultiValues(this.getAttribute('horizontal-align'), ['start', 'center', 'end'], ['flex-start', 'center', 'flex-end'], defaultConfig.container.horizontalAlign);
    const bgColor = this._attributeManager.processColor(this.getAttribute('bg-color'), defaultConfig.container.bgColor);
    const selectedBgColor = this._attributeManager.processColor(this.getAttribute('selected-bg-color'), defaultConfig.container.selectedBgColor);
    const scopeId = this.getAttribute('scope') || '';
    this._elementId = scopeId;
    const style = document.createElement('style') as HTMLStyleElement;
    style.textContent = `
      .${scopeId} {
        display: flex;
        width: ${width};
        height: ${height};
        font-family: Arial, sans-serif;
        flex-direction: ${vertical === false ? 'row' : 'column'};
        z-index: 99;
      }

      .${scopeId} tab-bar-item {
        display: flex;
        color: ${unselectedColor};
        flex-direction: ${layoutMode};
        align-items: ${verticalAlign};
        justify-content: ${horizontalAlign};
        background: ${bgColor};
        flex: 1;
      }

      .${scopeId} tab-bar-item:hover {
        color: ${selectedColor};
      }

      .${scopeId} tab-bar-item[name='${this._selectedItem}'] {
        color: ${selectedColor};
        background: ${selectedBgColor};
      }
    `;
    this._styleElement = style;
    document.head.appendChild(style);
  }

  registerEvents(callback: (param: any) => void): void {
    const navInstance = document.querySelectorAll(`*[scope=${this._elementId}]`);
    const navItems = navInstance[0].querySelectorAll('tab-bar-item');
    if (navItems.length) {
      navItems.forEach((item, index) => {
        item.addEventListener('click', (e) => {
          const nameAttr = item.getAttribute('name') || '';
          if (this._selectedItem !== nameAttr) {
            this._selectedItem = nameAttr;
            this._attachStyles();
          }
          e.preventDefault();
          this._eventManager.emit('tabItemClick', {
            index,
            name: nameAttr
          });
        });
      });
      this._eventManager.on('tabItemClick', callback);
    }
  }
}

if (!customElements.get('tab-bar')) {
  customElements.define('tab-bar', TabBarComponent);
}